package com.km.wskj.itmonitor.pager.wq.note;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.wq.note.model.NoteBook;
import com.km.wskj.itmonitor.pager.wq.note.model.NoteList;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.http.callback.StringCallback;
import com.zxl.zxlapplibrary.util.GalleryHelper;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

public class NoteListActivity extends LActivity {

    private static final String TAG = "NoteListActivity";

    @BindView(R.id.zlistview)
    ZrcListView zListView;

    //args
    NoteBook nb;

    //base data
    List<NoteList> noteList;

    //data
    int pageIndex;
    int lastUpdateNum;
    //adapter
    MyAdapter adapter;
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.activity_note_list)
    LinearLayout activityNoteList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_list);
        ButterKnife.bind(this);
        //args
        if (getIntent().hasExtra("nb")) {
            nb = (NoteBook) getIntent().getSerializableExtra("nb");
            //ui
            toolBarTitle.setText(nb.typeName);
        }
        toolBarBack.setVisibility(View.VISIBLE);
        onRefresh();
        initPullToRefresh();
        //load
        loadNotebookList();
    }


    private void loadNotebookList() {
        pdc.noteList(HTTP_TASK_TAG, 1, 16, nb.idX, new ZxlGenericsCallback<List<NoteList>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("获取笔记本列表失败!");
                LogUtils.e("error get notebooklist " + call.request().url().toString(), e);
            }

            @Override
            public void onResponse(List<NoteList> nl, int i) {
                noteList = nl;
            }
        });
    }

    @OnClick(R.id.action_note_text)
    public void onActionNoteText(View view) {
        Intent t = new Intent(context, AddNoteActivity.class);
        t.putExtra("nbId", nb.idX);
        startActivityForResult(t, 1);
    }

    @OnClick(R.id.action_note_pic)
    public void onActionNotePic(View view) {
        new GalleryHelper().openCamera(context, new GalleryHelper.OnPickPhotoCallback() {
            @Override
            public void onPickSucc(PhotoInfo photoInfo) {
                String picpath = photoInfo.getPhotoPath();
                Intent t = new Intent(context, AddNoteActivity.class);
                t.putExtra("nbId", nb.idX);
                t.putExtra("picpath", picpath);
                startActivity(t);
            }

            @Override
            public void onPickFail(String s) {
                showErrorTip(s);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case RESULT_OK:
                onRefresh();
                break;
            default:
                break;
        }
    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        zListView.setDivider(line);
        zListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(getResources().getColor(R.color.colorPrimary));
        zListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        zListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        //zListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        zListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        zListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        zListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                NoteList p = (NoteList) parent.getItemAtPosition(position);
                Intent t = new Intent(context, NoteDetailActivity.class);
                t.putExtra("data", p);
                startActivity(t);
            }
        });

       /* zListView.setOnItemLongClickListener(new ZrcListView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(ZrcListView zrcListView, View view, int i, long l) {

                final NoteList p = (NoteList) zrcListView.getItemAtPosition(i);
                final AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("提示？");
                builder.setMessage("您确定要删除？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        pdc.delNote(HTTP_TASK_TAG, p.id, new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int i) {
                                LogUtils.e(TAG, e);
                            }

                            @Override
                            public void onResponse(String s, int i) {
                                showToast("删除成功");
                                onRefresh();
                            }
                        });
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();

                return true;
            }
        });*/

        adapter = new MyAdapter();
        zListView.setAdapter(adapter);
    }

    private void onRefresh() {
        pdc.noteList(HTTP_TASK_TAG, 1, 16, nb.idX, new ZxlGenericsCallback<List<NoteList>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                zListView.setRefreshFail("数据获取失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<NoteList> o, int i) {
                noteList = o;
                lastUpdateNum = o.size();
                pageIndex = 1;
                //control
                adapter.notifyDataSetChanged();
                zListView.setRefreshSuccess();
                if (haveMore()) {
                    zListView.startLoadMore();
                } else {
                    zListView.stopLoadMore();
                }

            }
        });
    }

    private void onLoadMore() {
        LogUtils.d("onload more");
        pdc.noteList(HTTP_TASK_TAG, pageIndex + 1, 16, nb.idX, new ZxlGenericsCallback<List<NoteList>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                zListView.setRefreshFail("数据获取失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<NoteList> o, int i) {
                lastUpdateNum = o.size();
                if (o.size() > 0) {
                    noteList.addAll(o);
                    pageIndex++;
                }
                //control
                adapter.notifyDataSetChanged();
                zListView.setLoadMoreSuccess();
                if (haveMore()) {
                    zListView.startLoadMore();
                } else {
                    zListView.stopLoadMore();
                }
            }
        });
    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    @OnClick(R.id.tool_bar_back)
    public void onClick() {
        finish();
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (noteList != null) {
                return noteList.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return noteList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final NoteList note = (NoteList) getItem(position);
            BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_note);
            helper.setText(R.id.tv_title, note.title);
            helper.setText(R.id.tv_date, note.createTime);

            ImageView btn_check = helper.getView(R.id.btn_check);
            btn_check.setVisibility(View.GONE);
            btn_check.setImageResource(note.ischecked ? R.mipmap.icon_note_check_on : R.mipmap.icon_note_check_off);
            return helper.getView();
        }
    }
}
